/*
 * extra_timer.cpp
 *
 *  Created on: 2021年2月7日
 *      Author: kimfeng
 */

#include "extra_timer.h"
#include <list>
#include <boost/bind/bind.hpp>
#include <boost/thread/mutex.hpp>

typedef struct timer_info_s
{
	TimerProcFunc func;
	int expire_seconds;
	int timeout;
}timer_info_t;
typedef std::list<timer_info_t> ListTimerInfo;

static boost::asio::deadline_timer *g_timer = NULL;
static ListTimerInfo g_info;
static boost::mutex g_mutex;

void ExtraTimerInit(boost::asio::io_service& io_svc)
{
	g_timer = new boost::asio::deadline_timer(io_svc);
}

void ExtraTimerDeinit()
{
	delete g_timer;
}

static void handle_timeout()
{
	g_mutex.lock();
	ListTimerInfo::iterator it = g_info.begin();
	for (; it != g_info.end(); it++)
	{
		it->timeout--;
		if (it->timeout <= 0)
		{
			it->timeout = it->expire_seconds;
			if (it->func) it->func();
		}
	}
	g_mutex.unlock();
	g_timer->expires_from_now(boost::posix_time::seconds(1));
	g_timer->async_wait(boost::bind(&handle_timeout));
}

void ExtraTimerStart()
{
	g_timer->expires_from_now(boost::posix_time::seconds(1));
	g_timer->async_wait(boost::bind(&handle_timeout));
}

void ExtraTimerAttech(TimerProcFunc func, int expire_seconds)
{
	timer_info_t info;
	info.func = func;
	info.expire_seconds = expire_seconds;
	info.timeout = expire_seconds;
	g_info.push_back(info);
}

